package com.platform.license.client;

import com.platform.license.model.LicKeyStoreParam;
import de.schlichtherle.license.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.InputStream;
import java.util.Objects;
import java.util.prefs.Preferences;

/**
 * Description: License校验类
 *
 * @author libinal Created on 2019/9/22
 */
@Slf4j
public class LicenseVerify {
    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 安装License证书
     *
     * @param param 参数
     */
    public synchronized void install(LicenseVerifyParam param) {
        if (Objects.isNull(param)) {
            throw new RuntimeException("证书安装失败，证未找到证书");
        }

        String license = param.getLicensePath();
        File licensePath = new File(license);
        if (!licensePath.exists()) {
            throw new RuntimeException("证书安装失败，证未找到证书：" + licensePath);
        }

        Resource resource = new FileSystemResource(param.getLicensePath());
        // 1. 安装证书
        try (InputStream in = resource.getInputStream()) {
            LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(initLicenseParam(param));
            licenseManager.uninstall();
            File licFile = File.createTempFile("license", "lic");
            FileUtils.copyInputStreamToFile(in, licFile);
            LicenseContent content = licenseManager.install(licFile);
            if (log.isDebugEnabled()) {
                log.debug("证书安装成功，证书有效期：{} - {}", DateFormatUtils.format(content.getNotBefore(), DATE_TIME_PATTERN),
                        DateFormatUtils.format(content.getNotAfter(), DATE_TIME_PATTERN));
            }
        } catch (Exception e) {
            throw new RuntimeException("证书安装失败：" + e.getMessage());
        }
    }

    /**
     * 校验License证书
     *
     * @return boolean
     */
    public boolean verify() {
        LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(null);
        // 校验证书
        try {
            LicenseContent content = licenseManager.verify();
            if (log.isDebugEnabled()) {
                log.debug("证书安装成功，证书有效期：{} - {}", DateFormatUtils.format(content.getNotBefore(), DATE_TIME_PATTERN),
                        DateFormatUtils.format(content.getNotAfter(), DATE_TIME_PATTERN));
            }
            return true;
        } catch (Exception e) {
            System.out.println("证书校验失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 初始化证书生成参数
     *
     * @param param 证书参数
     * @return LicenseParam
     */
    private LicenseParam initLicenseParam(LicenseVerifyParam param) {
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);
        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
        KeyStoreParam keyStoreParam = new LicKeyStoreParam(
                LicenseVerify.class,
                param.getPublicKeysStorePath(),
                param.getPublicAlias(),
                param.getStorePass(),
                null
        );
        return new DefaultLicenseParam(param.getSubject(), preferences, keyStoreParam, cipherParam);
    }
}
